<template>
  <div id="map">
    <baidu-map
      :style="mapstyle"
      class="echarts"
      :center="center ? center : { lng: 116.418261, lat: 39.921984 }"
      :zoom="proportion ? proportion : 5"
      @ready="handler"
      :scroll-wheel-zoom="true"
      ak="EStrXQgEpuk6v4o2zYklNB50D59zmhvm"
    >
      <!-- ak="lLBCDtYMaiuWAZCi1yYc5XF6eb39B4Do" -->

      <!--比例尺控件-->
      <bm-scale anchor="BMAP_ANCHOR_TOP_LEFT"></bm-scale>
      <!--缩放控件-->
      <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
      <!-- 行政区划图 -->
      <bm-boundary
        v-for="item in echartsData"
        :key="item.area"
        :name="item.area"
        :zoom="1"
        :strokeWeight="0.1"
        strokeColor="#ffffff"
        :strokeOpacity="0"
        :fillColor="item.color"
        :fillOpacity="0.5"
        @mouseover="look(item)"
        @click="look(item)"
        @mouseout="infoWindowClose()"
      ></bm-boundary>

      <!-- <bm-info-window
        v-for="item in echartsData"
        :key="item.id"
        class="window_style"
        :position="item"
        :show="show"
        @close="infoWindowClose"
        @open="infoWindowOpen"
        style="font-size: 13px"
      >
        <div class="info_window">
          {{ item.area }}
          {{ item.the_data }}
        </div>
      </bm-info-window> -->

      <bm-info-window
        class="window_style"
        v-if="maker"
        :position="maker"
        :show="show"
        @close="infoWindowClose"
        @open="infoWindowOpen"
        style="font-size: 13px"
      >
        <div class="info_window">
          {{ maker.area }}
          {{ maker.the_data }}
        </div>
      </bm-info-window>

      <!-- 点图 -->
      <my-overlay
        v-for="(item, index) in markers"
        :key="index"
        :position="item"
        :text="item"
        :sizeParams="mapSize"
      >
      </my-overlay>

      <bm-marker
        v-for="item in markers"
        :key="item.area"
        :position="item"
        :dragging="true"
        @click="look(item)"
        @mouseover="look(item)"
        @mouseout="infoWindowClose()"
        :icon="{
          url: require('../../../assets/round.png'),
          size: {
            width: 20,
            height: 20,
          },
        }"
      >
      </bm-marker>
    </baidu-map>

    <div v-show="legendShow" class="color_bar"></div>
    <canvas
      ref="cvs"
      v-show="legendShow"
      class="canvas_dom"
      width="120"
      height="200"
    ></canvas>
  </div>
</template>

<script>
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
// 比例尺控件
import BmScale from "vue-baidu-map/components/controls/Scale";
import { BmBoundary } from "vue-baidu-map";

// 缩放控件
import BmNavigation from "vue-baidu-map/components/controls/Navigation";
// 点聚合
import BmMarkerClusterer from "vue-baidu-map/components/extra/MarkerClusterer";
// 点
import BmMarker from "vue-baidu-map/components/overlays/Marker";
// 信息窗体
import BmInfoWindow from "vue-baidu-map/components/overlays/InfoWindow";
// 热力图
import BmlHeatmap from "vue-baidu-map/components/extra/Heatmap";
import MyOverlay from "./MyOverLay.vue";

export default {
  props: {
    mapData: {
      type: Array,
    },
    mapSize: {
      type: Number,
    },
    unit: {
      type: String,
    },
    center: {
      type: Object,
      default: function () {
        return { lng: 116.418261, lat: 39.921984 };
      },
    },

    proportion: {
      type: Number,
      default: function () {
        return 5;
      },
    },
  },
  components: {
    BmScale,
    BaiduMap,
    BmNavigation,
    BmlHeatmap,
    BmMarker,
    BmInfoWindow,
    MyOverlay,
    BmBoundary,
  },
  data() {
    return {
      // center: { lng: 116.418261, lat: 39.921984 },
      echartsData: [],
      zoom: 5,
      echarts: [],
      markers: [],
      show: true,
      maker: null,
      BMap: null,
      map: null,
      data: [
        { lng: 125.350525, lat: 43.859504, count: 5820 },
        { lng: 119.520968, lat: 35.972779, count: 6000 },
        { lng: 114.923953, lat: 37.632187, count: 5940 },
        { lng: 126.100489, lat: 46.710685, count: 5700 },
      ],
      administrative: [],
      legendShow: true,
      markerShow: true,
      sizeParams: "",
      mapstyle: "",
    };
  },

  watch: {
    mapSize: {
      handler(newData) {
        if (newData) {
          this.sizeParams = newData;
        }
      },
      immediate: true,
      deep: true,
    },

    mapData: {
      handler(newData) {
        let data = newData[0].dataList;
        if (data) {
          if (data.length >= 2 && data[1].color) {
            this.echartsData = data;
            // this.look();
            this.$nextTick(() => {
              this.showCanvas();
            });
          } else {
            this.echartsData = [];
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },

  created() {
    // 获取interval的最高ID然后遍历清除
    const HIGHEST_INTERVAL_ID = setInterval(";");
    for (let i = 0; i < HIGHEST_INTERVAL_ID; i++) {
      clearInterval(i);
    }
  },

  mounted() {
    this.worldMapContainer = document.getElementById("map");
    //设置容器高宽
    this.resizeWorldMapContainer();
  },

  destroyed() {
    this.distroyMap();
  },

  methods: {
    initMap() {
      // if (!this.map.loaded) return;
      // this.map.clearOverlays();
      // this.map.centerAndZoom(this.center, this.zoom);
    },

    //用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
    resizeWorldMapContainer() {
      let height = window.innerHeight - 2 + "px";
      this.worldMapContainer.style.height = window.innerHeight - 2 + "px";
      this.mapstyle = `height: ${height}`;
    },

    formatInt(num, prec = 2, ceil = true) {
      const len = String(num).length;
      if (len <= prec) {
        return num;
      }
      const mult = Math.pow(10, prec);
      return ceil
        ? Math.ceil(num / mult) * mult
        : Math.floor(num / mult) * mult;
    },

    distroyMap() {
      try {
        // 注销地图（换成你初始化时定义的地图变量）
        this.map = null;
        // 获取interval的最高ID然后遍历清除
        const HIGHEST_INTERVAL_ID = setInterval(";");
        for (let i = 0; i < HIGHEST_INTERVAL_ID; i++) {
          clearInterval(i);
        }
        // 获取百度地图创建的DOM并销毁
        const BAIDU_MAPS = document.querySelectorAll(
          ".tangram-suggestion-main"
        );
        BAIDU_MAPS.forEach((item) => {
          document.body.removeChild(item);
        });
      } catch (e) {}
    },

    getData(echarts) {
      this.initMap();
      this.echarts = [];
      if (echarts) {
        this.echarts = echarts[0].dataList;
        if (this.echarts[0].color) {
          this.legendShow = true;
        } else {
          this.legendShow = false;
        }
      }
      if (this.echarts && this.echarts.length > 0) {
        this.echarts.forEach((e) => {
          if (e.lng != undefined && e.lat != undefined && !e.color) {
            this.markers.push({
              lng: e.lng,
              lat: e.lat,
              area: e.area,
              value: e.the_data,
              unit: e.unit,
            });
          }
        });
      }
    },
    //展示图例
    showCanvas() {
      let canvas = this.$refs.cvs;
      let ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, 600, 600);
      let arr = [...this.echartsData].splice(1, this.echartsData.length - 1);
      arr = arr.map((item) => item.the_data);

      arr.sort((a, b) => {
        return a - b;
      });
      let min = Math.round(Number(arr[0]));
      let minDigits = min.toString().length;
      min = this.formatInt(min, minDigits - 2, false);

      let max = Math.round(Number(arr[arr.length - 1]));
      let maxDigits = max.toString().length;
      max = this.formatInt(max, maxDigits - 2, true);

      let median = Math.round((max + min) / 2);
      let medianDigits = median.toString().length;
      median = this.formatInt(median, medianDigits - 2, true);

      let maxMedian = Math.round((max + median) / 2);
      let maxMedianDigits = maxMedian.toString().length;
      maxMedian = this.formatInt(maxMedian, maxMedianDigits - 2, true);

      let minMedian = Math.round((min + median) / 2);
      let minMedianDigits = minMedian.toString().length;
      minMedian = this.formatInt(minMedian, minMedianDigits - 2, false);

      let legendData = ["", max, maxMedian, median, minMedian, min];
      for (var i = 0; i < legendData.length; i++) {
        var item = legendData[i];
        ctx.fillText(item, 24, 12 + (i - 1) * 36);
        ctx.font = "12px Arial";
        ctx.fillStyle = "black";
      }
      ctx.fillText("单位：" + this.unit, 10, 190);
    },

    showTip(target) {},

    handler({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
    },

    async look(item) {
      console.log("item", item);
      // area: "新疆维吾尔自治区";
      // color: "#00D1FF";
      // the_data: "22939231";
      this.maker = item;
      await this.infoWindowOpen();
    },

    infoWindowClose() {
      // this.show = false;
    },

    infoWindowOpen() {
      this.show = true;
    },
  },
};
</script>

<style lang="scss">
.echarts {
  background-color: #ffffff;
  border-radius: 7px;
  margin-top: -6px;
}
.color_bar {
  z-index: 9999999999;
  position: absolute;
  bottom: 70px;
  right: 140px;
  height: 160px;
  width: 20px;
  opacity: 0.6;
  background: url("~@/assets/line.png");
  background-size: 100% 100%;
}

.canvas_dom {
  position: absolute;
  bottom: 30px;
  right: 20px;
}

.background {
  position: absolute;
  z-index: 111;
  bottom: 30px;
  right: 300px;
  width: 140px;
  height: 320px;
  opacity: 0.2;
}
.info_window {
  width: auto;
  height: 0px;
  padding-left: 100px;
  line-height: 0px;
  color: #343434;
}

.BMap_shadow {
  display: none !important;
}

.BMap_bottom {
  display: none;
}
.BMap_pop {
  > div,
  > img:nth-child(10) {
    display: none;
    overflow: unset;
  }
  > div:nth-child(9) {
    display: block;
    overflow: unset;
    width: 340px !important;
  }

  .BMap_top {
    display: none;
  }
  .BMap_center {
    background: transparent;
    border: none;
    position: sticky !important;
    height: 100%;
  }
}
.BMap_bubble_content {
  padding-top: 30px;
  padding-left: 30px;
  margin-top: 28px;
  .info-window {
    padding-right: 8px;
    width: 100%;
    max-height: 280px;
    color: #ccc !important;
    overflow: hiden;

    .address {
      color: #fff;
    }
  }
}
</style>
